# last 6411c6d36b41ee35a848067e
from optparse import Option
import time
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
import pymongo
from selenium.webdriver.edge.options import Options
from dao.BaseRepository import BaseRepository
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
option=Options()
option.add_argument(r"--user-data-dir=D:\\git\\gamecrawer\\gamecrwaer\browser-user-data")
browser = webdriver.Edge(r"D:\\git\\gamecrawer\\gamecrwaer\\edgedriver_win64\\msedgedriver.exe",options=option)

baseRep = BaseRepository(collectionname="xdgame")

# baseRep = BaseRepository(collectionname="gamecrawer")


def main():
    # result, num, msg = baseRep.get_all_no_page(sort=[("modifyTime", -1)])
    results, _, _ = baseRep.get_all_no_page(sort=["_id",pymongo.DESCENDING])

    url = 'https://pan.baidu.com'

    # 声明浏览器
    browser.get(url)

    # time.sleep(1)
    # # browser.close()  # 关闭浏览器
    #
    # browser.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__footerULoginBtn"]').click()
    # browser.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__userName"]').send_keys("terrydash")
    # time.sleep(1)
    # browser.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__password"]').send_keys("52xuguoxu")
    # browser.get_screenshot_as_file("a.png")
    # browser.find_element_by_xpath('// *[ @ id = "TANGRAM__PSP_4__submit"]').click()

    # r = browser.find_element_by_xpath('//*[@id="dialog1"]/div[2]/div/div[2]')
    # if r:
    #     r.click()
    time.sleep(30)
    rs = browser.find_elements(By.CSS_SELECTOR,"div.file-name > div.text > a")
    browser.find_element
    print(len(rs))

    for r in results:
        print(r.get("name"))
        print(r.get("_id"))
        status = r.get("status", "need_save")

        if "pan.baidu.com" in str(r.get("pan_link")).lower() and len(r.get("pan_link")) > 0 :# and status != "saved":
            pan_url = str(r.get("pan_link")).split("?")[0]
            browser.get(pan_url)

            time.sleep(3)
            if len(r.get("pan_code")) > 0 :
                try:
                    browser.find_element(By.ID,
                        "accessCode").send_keys(r.get("pan_code"))
                    time.sleep(2)
                    browser.find_element(By.CLASS_NAME,"submit-btn-text").click()

                except Exception as e:
                    print(e)
            print("全选")
            error_num = 0
            time.sleep(2)
            while error_num < 5:
                try:
                    browser.find_element(By.XPATH,
                        '//*[@id="shareqr"]/div[2]/div[2]/div/ul[1]/li[1]/div/span[1]').click()
                    time.sleep(2)
                    browser.find_element(By.XPATH,
                        '//*[@id="bd-main"]/div/div[1]/div/div[3]/div/div/div[2]/a[1]/span/span').click()
                    time.sleep(2)
                    WebDriverWait(browser, 10).until(EC.presence_of_element_located(
                        (By.XPATH, '//*[@id="fileTreeDialog"]/div[4]/a[2]/span/span')))
                    browser.find_element(By.XPATH,
                        '//*[@id="fileTreeDialog"]/div[4]/a[2]/span/span').click()
                    # WebDriverWait(browser, 10).until(EC.presence_of_element_located(
                    #     (By.XPATH, '//*[@id="emptyDialogId"]/div/div[2]/div[1]')))
                    break
                except Exception as e:
                    time.sleep(3)
                    print(e)
                    error_num += 1
                if error_num > 5:
                    continue

            r["status"] = "saved"
            baseRep.update_by_id(r.get("_id"), r)
            time.sleep(3)

    #     if "downloadUrl" in r and len(str(r.get("downloadUrl"))) > 0 and str(r.get("downloadUrl")).startswith(
    #             "https://pan.baidu"):
    #         r["downloadUrl"] = str(r.get("downloadUrl")).replace("https://pan.baidu.chttps://pan.baidu.com/s",
    #                                                              "https://pan.baidu.com/s")
    #         try:
    #             baidupan_save(r.get("downloadUrl"), r)
    #             time.sleep(1)
    #         except Exception as e:
    #             hslogger.error(e)
    #             continue


def baidupan_save(url, r):
    browser.get(url)

    try:
        if len(str(r.get("downloadPassword"))) > 0 and browser.find_element_by_class_name(
                "g-button-right") is not None and browser.find_element_by_class_name(
                "input-area") is not None and browser.find_element_by_class_name("input-area").find_element_by_tag_name(
                "input") is not None:
            browser.find_element_by_class_name("input-area").find_element_by_tag_name("input").send_keys(
                r.get("downloadPassword"))
            browser.find_element_by_class_name("g-button-right").click()
            time.sleep(10)

    finally:
        pass
    time.sleep(1)
    try:
        if len(browser.find_elements_by_xpath('//*[@id="share_nofound_des"]')) == 0:
            browser.find_element_by_xpath(
                '//*[@id="shareqr"]/div[2]/div[2]/div/ul[1]/li[1]/div/span[1]').click()
            time.sleep(1)
            browser.find_element_by_xpath(
                '//*[@id="bd-main"]/div/div[1]/div/div[2]/div/div/div[2]/a[1]').click()
            time.sleep(1)
            browser.find_element_by_class_name("g-button-blue-large").click()
            time.sleep(2)
    finally:
        pass


if __name__ == "__main__":
    main()
